package ru.stepuk.modern.nodes.servers;

import java.util.HashMap;
import java.util.Map;
import javax.swing.ImageIcon;
import ru.stepuk.modern.InvalidModelException;
import ru.stepuk.modern.Model;
import ru.stepuk.modern.Request;
import ru.stepuk.modern.Timeline;
import ru.stepuk.modern.distributions.Distribution;
import ru.stepuk.modern.events.ReleaseServer;

/**
 *
 * @author ivan
 */
public class PriorityServer extends Server implements Interruptive {

    private boolean lastServed = false;
    private long nextReleaseTime = 0;
    private Map<Request, Double> table = new HashMap<Request, Double>();

    {
        icon = new ImageIcon(getClass().getResource("/images/d_prior.png"));
    }

    public PriorityServer(Model model, Timeline timeline, Distribution distribution) {
        super(model, timeline, distribution);
    }

    @Override
    public void processRequest(Request request) {
       System.out.println(timeline.now() + ": " + name + "request come to Pserver");
        if (idle) {
            // Normal
            

            double time = 0;
            if (table.containsKey(request)) {
                time = table.get(request);
            } else {
                time = distribution.nextValue();
                table.put(request, time);
            }
            currentRequest = request;
            idle = false;
            nextReleaseTime = timeline.addEvent(timeline.now() + time, new ReleaseServer(this));

        } else if (currentRequest.getPriority() < request.getPriority()) {
            // Interruption
            System.out.println("interruption");
            // Kick old...
            table.put(currentRequest, nextReleaseTime - timeline.now());
            timeline.deleteEvent(nextReleaseTime);
            lastServed = false;
            next.processRequest(currentRequest);

            currentRequest = null;
            idle = true;
            this.processRequest(request);

        } else if ((buffer != null) && (buffer.hasFreeSpace())) {
            buffer.putRequest(request);
            System.out.println("put in buffer");
        } else {
            
            System.out.println("Request faiued");
        }


    }

     @Override
    public void releaseRequest() {
        lastServed = true;
        table.remove(currentRequest);
        super.releaseRequest();
    }

    @Override
    public void validate() throws InvalidModelException {
        super.validate();
        table.clear();
    }

    public boolean lastServeSuccessfull() {
        return lastServed;
    }
}
